package com.shuai.baibi.mq;

import com.rabbitmq.client.Channel;
import com.shuai.baibi.common.ErrorCode;
import com.shuai.baibi.constant.BIMQConstant;
import com.shuai.baibi.exception.BusinessException;
import com.shuai.baibi.manager.XunFeiAPIManager;
import com.shuai.baibi.model.entity.Chart;
import com.shuai.baibi.model.enums.ChartStatusEnum;
import com.shuai.baibi.service.ChartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;

@Component
@Slf4j
public class BIChartMessageMQConsumer {

    @Autowired
    private ChartService chartService;

    @Autowired
    private XunFeiAPIManager xunFeiAPIManager;

    @RabbitListener(queues = {BIMQConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void consumeMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliverTag) throws IOException {
        if (StringUtils.isBlank(message)) {
            channel.basicAck(deliverTag, Boolean.FALSE);
            log.error("MQ-Consumer-从消息队列中获取到的消息为blank，MQMessage:{}", deliverTag);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "从消息队列中获取到的消息为blank");
        }
        long chartId = Long.parseLong(message);

        // 根据消息队列拿到的消息从数据库中查询该条消息的信息
        Chart chartOriginal = chartService.getById(chartId);    // 用户上传的图表数据
        if (chartOriginal == null) {
            log.error("MQ-Consumer-根据消息tag：" + deliverTag + " 无法查询到对应的图表信息");
            channel.basicAck(deliverTag, Boolean.FALSE);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "MQ-Consumer-根据消息tag：" + deliverTag + " 无法查询到对应的图表信息");
        }

        String goal = chartOriginal.getGoal();  // 用户上传的分析目标
        String chartType = chartOriginal.getChartType();    // 用户上传的图表类型
        String chartData = chartOriginal.getChartData();    // 用户上传的处理后的图表数据（csv）

        String askStr = chartService.buildXFAskStr(goal, chartType, chartData); // 构建AI请求语句

        // 先更新图表分析表中的数据为running-1处理中状态
        chartOriginal.setStatus(ChartStatusEnum.RUNNING.getStatus());
        if (!chartService.updateById(chartOriginal)) {
            log.error("【" + LocalDateTime.now() + "】error-数据库服务异常-保存chart" + BIChartMessageMQConsumer.class);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "服务异常，正在加急修复中...");
        }
        String responseMessage = null;
        Map<String, String> responseMap = null;
        // 调用AI接口并取得返回结果
        try {
            responseMessage = xunFeiAPIManager.ask(askStr);
        } catch (Exception e) {
            log.error("[" + LocalDateTime.now() + "]调用AI请求分析图表出错,图表数据：" + chartOriginal);
            // 更新图表信息表中的图表状态为2-failed
            chartOriginal.setStatus(ChartStatusEnum.FAILED.getStatus());
            chartService.setExecMessage(chartOriginal, "分析图表数据失败，请尝试重新提交（-1）");
            return;
        }
        // 对相应数据进行处理
        try {
            responseMap = chartService.processXFResponseData(responseMessage);
        } catch (Exception e) {
            log.error("[" + LocalDateTime.now() + "]AI响应数据格式异常：" + chartOriginal);
            // 更新图表信息表中的图表状态为2-failed
            chartOriginal.setStatus(ChartStatusEnum.FAILED.getStatus());
            chartService.setExecMessage(chartOriginal, "分析图表数据失败，请尝试重新提交（-2）");
            return;
        }
        if (responseMap == null || responseMap.isEmpty()) {
            log.error("【" + LocalDateTime.now() + "】error-AI接口响应数据格式错误" + BIChartMessageMQConsumer.class);
            chartOriginal.setStatus(ChartStatusEnum.FAILED.getStatus());
            chartService.setExecMessage(chartOriginal, "分析图表数据失败，请尝试重新提交（-3）");
            return;
        }
        // 保存图表数据
        chartOriginal.setStatus(ChartStatusEnum.SUCCEED.getStatus());
        chartOriginal.setExecMessage("");
        chartOriginal.setGenChartData(responseMap.get("genChartData"));
        chartOriginal.setGenChartResult(responseMap.get("genChartResult"));
        if (!chartService.updateById(chartOriginal)) {
            log.error("AI生成的图表数据保存失败！数据库服务异常。{}", chartOriginal);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "服务异常，正在快马加鞭修复中...");
        }
        channel.basicAck(deliverTag, false);
    }
}
